package se.webbzon.boltzmann.game.event;

import java.util.Collection;

import se.webbzon.boltzmann.game.sequence.Sequence;
import se.webbzon.boltzmann.game.sequence.Sequences;
import se.webbzon.boltzmann.item.AbstractItem;
import se.webbzon.boltzmann.item.ItemGroup;
import se.webbzon.oschi01.worldarea.WorldArea;

public class ItemToIdEvent extends AbstractGameEvent {
	
	// The sequence associated with this game event
	private final Sequence sequence;

	/*============================================================
	Constructors
	============================================================*/

	/** Puts the id of the item with the id or name argument[0] at
	 * the variable argument[1]. **/
	public ItemToIdEvent(	String[] arguments, Sequence sequence) {
		super(arguments);
		this.sequence = sequence;
	}

	/*============================================================
	Public Methods
	============================================================*/

	@Override protected void onBegin(WorldArea world) {
		if (arguments() >= 2) {
			final Object item = Sequences.parse(sequence, getArgument(0));
			final ItemGroup ig = ItemGroup.instance();
			
			// Retrieve the item
			final AbstractItem it;
			if (item instanceof String) {
				Collection<AbstractItem> items = ig.getItems((String) item);
				if (items.isEmpty())
					it = null;
				else
					it = items.iterator().next();
			} else
				it = ig.getItem((int) (double) item);
			
			if (it != null)
				Sequences.set(sequence, getArgument(1), (double) ig.getId(it));
			else
				exception(	"The item with the identifier " +
							"\"" + item + "\" was not found!");
		} else
			exception("Argument exception.");
		end();
	}

	@Override protected void onEnd() {};

}
